import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Button, Select, Modal, message, Form, Input, Radio, Upload, InputNumber } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { cachetaskEdit, cachetaskSearch } from '@/services/server';
import StorageManager from '@/utils/StorageManager';
import { cloneDeep } from 'lodash';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';

import DetailModel from '../DetailModel';
import styles from './style.less';

let timeout: ReturnType<typeof setTimeout> | null;
// @ts-ignore
let currentValue: string;

const BatchTicketList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modalNumForm] = Form.useForm();

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [visibleDetailModel, setVisibleDetailModel] = useState<boolean>(false);
  // @ts-ignore
  const [fileUrlBro, setFileUrlBro] = useState<string>();

  const activityWatch = Form.useWatch('activity', modalNumForm);
  // @ts-ignore
  const activityListWatch = Form.useWatch('activityList', modalNumForm);
  const typeWatch = Form.useWatch('type', modalNumForm);

  const [dataOption, setDataOption] = useState<any>([
    {
      value: '测试1',
      text: '测试1',
    },
    {
      value: '测试2',
      text: '测试2',
    },
  ]); // 下拉框--option 枚举值
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelNumVisible, setModelNumVisible] = useState<boolean>(true);

  // 提交
  const handleOperate = async (record: any, type: string) => {
    if (type === '明细') {
      setVisibleDetailModel(true);
      setTimeout(() => {
        setVisibleDetailModel(false);
      });
      return;
    }
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '活动定义',
      dataIndex: 'updateUser',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '执行状态',
      dataIndex: 'updateUser1',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
      valueEnum: {
        0: { text: '全部' },
        1: { text: '导入成功' },
        2: { text: '已完成' },
        3: { text: '失败' },
        4: { text: '部分成功' },
      },
      initialValue: '全部',
    },
    {
      title: '任务类型',
      dataIndex: 'updateUser2',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
      valueEnum: {
        0: { text: '全部' },
        1: { text: '单人发券' },
        2: { text: '批量发券' },
      },
      initialValue: '全部',
    },
    // 表格
    {
      title: '活动定义',
      dataIndex: 'cacheKey',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动代码',
      dataIndex: 'cacheValue',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券名',
      dataIndex: 'lastUpdateTime',
      ellipsis: true,
      width: 190,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      dataIndex: 'updateUser',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'updateUser',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 60,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => handleOperate(record, '明细')}>明细</a>&nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await cachetaskSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  const handleNumOK = () => {
    modalNumForm.validateFields().then(async (values) => {
      console.log('values==', values);
      return;
      setConfirmLoad(true);
      const { code, data } = await cachetaskEdit({ ...values });
      if (code === 200 && data) {
        message.success('操作成功');
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  // 拉下option请求接口--防抖
  const fetch = (value: string, callback: Function) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    currentValue = value;

    const fake = () => {
      // const str = qs.stringify({
      //   code: 'utf-8',
      //   q: value,
      // });
      // jsonp(`https://suggest.taobao.com/sug?${str}`)
      //   .then((response: any) => response.json())
      //   .then((d: any) => {
      //     if (currentValue === value) {
      //       const { result } = d;
      //       const data = result.map((item: any) => ({
      //         value: item[0],
      //         text: item[0],
      //       }));
      //       callback(data);
      //     }
      //   });
      const data = [
        {
          value: '巴黎',
          text: '爱仕达',
        },
        {
          value: '巴黎1',
          text: '爱仕达1',
        },
      ];

      callback(data);
    };

    timeout = setTimeout(fake, 300);
  };

  // 下拉框输入时 掉接口
  const handleSearch = (newValue: string) => {
    console.log('newValue', newValue);
    if (newValue) {
      fetch(newValue, setDataOption);
    } else {
      // setDataOption([]);
    }
  };

  // 修改单个下拉
  const handleChange = (newValue: string[]) => {
    console.log('handleChange-newValue', newValue);
    const activityList = cloneDeep(modalNumForm.getFieldValue('activityList'));
    const activityListBro: any = [];
    newValue.forEach((item: any) => {
      const flag = activityList.find((i: any) => i.activityName === item);
      if (flag) {
        activityListBro.push({ activityName: item, activityNum: flag.activityNum });
      } else {
        activityListBro.push({ activityName: item, activityNum: 0 });
      }
    });
    console.log('前置条件-activityListBro', activityListBro);
    modalNumForm.setFieldValue('activityList', activityListBro);
  };

  const onFileChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    const { status, response } = file || {};
    setFileList(newFileList);

    // 没有status，说明没有上传，是本地文件
    if (!status) {
      setFileList([...fileList]);
    }
    if (status === 'uploading') {
      setLoading(true);
    }
    if (status === 'done') {
      const { code, data } = response || {};
      if (code === '200' && data) {
        setFileUrlBro(data);
      }
      setLoading(false);
    }
    if (status === 'error') {
      setLoading(false);
      setFileList([...fileList]);
      message.error('上传失败');
    }
  };

  const beforeUploadCrop = (file: File) => {
    const isOverSize = file.size / 1024;
    if (isOverSize > 20 * 1024) {
      message.error('文件大小必须小于20MB!');
      // message.error(`图片大小必须小于${maxSize}kb!`);
      return false;
    }
    return true;
  };

  console.log('嘎嘎嘎孟--activityWatch', activityWatch);

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.CodegroupListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              onClick={() => {
                setModelNumVisible(true);
              }}
            >
              新增发券
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title="新增发券"
          width={520}
          open={modelNumVisible}
          onOk={handleNumOK}
          onCancel={handleNumCancel}
          confirmLoading={confirmLoad}
          okText="提交"
          cancelText="返回"
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalNumForm}
            initialValues={{
              activity: [],
              activityList: [
                // {
                //   activityName: 'name1111',
                //   activityNum: '1111',
                // },
              ],
              cacheKey: '',
              cacheValue: '',
              type: 1,
              userType: 1,
              remark: '',
            }}
          >
            {/* <Form.Item label="id" name="id" style={{ width: 400 }} hidden>
              <Input />
            </Form.Item> */}
            <Form.Item label="活动定义" name="activity" style={{ width: 400 }}>
              <Select
                mode="multiple"
                showSearch
                // value={value}
                placeholder={'请选择'}
                defaultActiveFirstOption={false}
                showArrow={true}
                filterOption={false}
                onSearch={handleSearch}
                onChange={handleChange}
                notFoundContent={null}
                options={(dataOption || []).map((d: any) => ({
                  value: d.value,
                  label: d.text,
                }))}
                maxTagCount={'responsive'}
              />
            </Form.Item>

            <Form.List name="activityList">
              {(fields) => (
                <>
                  {fields.map((field) => (
                    <>
                      {console.log('field', field)}
                      <Form.Item
                        labelCol={{ span: 12 }}
                        label={[field.key, 'activityName']}
                        name={[field.name, 'activityNum']}
                        style={{ width: 400 }}
                      >
                        <InputNumber style={{ width: 150 }} min={0} />
                      </Form.Item>
                    </>
                  ))}
                </>
              )}
            </Form.List>

            <Form.Item label="发券类型" name="type" style={{ width: 400 }}>
              <Radio.Group>
                <Radio value={1}>单个用户</Radio>
                <Radio value={2}>批量导入</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="用户信息" name="userType" style={{ width: 400 }}>
              <Radio.Group>
                <Radio value={1}>手机号码</Radio>
                <Radio value={2}>用户标识</Radio>
              </Radio.Group>
            </Form.Item>
            {typeWatch === 1 ? (
              <Form.Item label="手机号码" name="cacheValue2" style={{ width: 400 }}>
                <Input />
              </Form.Item>
            ) : (
              <>
                <Form.Item label="文件导入" name="remark" style={{ width: 400 }}>
                  <Input placeholder="请输入备注信息" />
                </Form.Item>
                <Form.Item label={null} name="fileUrl" style={{ paddingLeft: 30 }}>
                  <Upload
                    name="file"
                    accept=".txt"
                    listType={'text'}
                    headers={{
                      ticket: `${StorageManager.getLocalStorageSync('token')}`,
                      contentType: 'multipart/form-data',
                    }}
                    fileList={fileList}
                    action={`${API_CONFIGS.server}${API_CONFIGS.prefix}/thirdpart/upload`}
                    beforeUpload={beforeUploadCrop}
                    onChange={onFileChange}
                  >
                    {fileList.length === 0 && (
                      <Button type="primary" loading={loading}>
                        文件上传
                      </Button>
                    )}
                  </Upload>
                </Form.Item>
              </>
            )}
          </Form>
        </Modal>

        <DetailModel visibleDetailModel={visibleDetailModel} />
      </div>
    </PageContainer>
  );
};

export default BatchTicketList;
